class UpdateDataController < ApplicationController

  # 从/deploy下扫描应用列表
  def apps
    command = 'find /deploy/*/config/deploy.rb|sed "s/\/deploy\///"|sed "s/\/.*//"'
    #获取编译打包机器信息
    package_host, port, user, password = view_context.get_package_host_info('测试')

    app_names_all = []
    #登录上线前部署机，获取app列表
    begin
      Net::SSH.start(package_host, user, :password => password, :port => port) do |ssh|
        ssh.exec!(command) do |ch, stream, data|
          if stream == :stdout
            data.force_encoding 'utf-8'
            p data
            p data.split("\n")
            app_names_all = data.split("\n")
          else
            logger.error data
          end
        end
      end
    rescue e
      logger.error '更新app列表失败: ' + e.message
      logger.error e.backtrace.join("\n")
    end

    apps = App.all
    app_names_saved = apps.collect { |app| app.name }
    app_names_tmp = Dir.glob('/deploy/*').select { |f| File.directory? f }.collect { |f| File.basename(f) }
    logger.info app_names_tmp

    app_names_new = app_names_all - app_names_saved

    app_names_new.each { |app_name|
      logger.info('new app %s' % app_name)
      @app = App.new(name: app_name)
      @app.save()
    }
    redirect_to root_path

  end
end
